package com.jsmtr.rms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IDoResumeService;
import com.jsmtr.rms.service.IResumeService;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.service.IMemberService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.EnumTools;
import com.jsmtr.rms.utils.StringTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/member")
public class SysMemberController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IMemberService memberService;

    @Autowired
    private IDoResumeService doResumeService;

    @Autowired
    private IResumeService resumeService;

    //[start] 注册用户管理
    @RequestMapping("/index")
    public String Index(HttpServletRequest request, Model model) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/member/index";
    }

    //获得应聘者信息
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getmembers", method = RequestMethod.POST)
    public void GetMembers(HttpServletRequest request, HttpServletResponse response, HRUsers user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> map = memberService.getResults(page, perpage, user);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (HRUsers usr : (List<HRUsers>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    if (usr.getHasresume() == EnumTools.IsOrNot.是.ordinal()) {
                        result.append("<td class='link'><a target='_blank' href='/Do/SZResume/ViewResumeCardno?cardno=" + usr.getUcode() + "'>" + usr.getUname() + "</a></td>");
                    } else {
                        result.append("<td>" + usr.getUname() + "</td>");
                    }
                    result.append("<td>" + usr.getUcode() + "</td>");
                    result.append("<td>" + usr.getUemail() + "</td>");
                    result.append("<td>" + usr.getTel() + "</td>");
                    result.append("<td>" + DateTools.toLenStr(usr.getAddtime()) + "</td>");
                    result.append("<td>" + DateTools.toLenStr(usr.getLogintime()) + "</td>");
                    result.append("<td>" + EnumTools.IsOrNot.values()[usr.getHasresume()] + "</td>");
                    if (usr.getUstate() == EnumTools.State.启用.ordinal()) {
                        result.append("<td class='false'><span>" + EnumTools.State.values()[usr.getUstate()] + "</span></td>");
                        result.append("<td class='link'><a href=\"javascript:enableuser('" + usr.getId() + "');\">禁用</a>");
                    } else {
                        result.append("<td class='true'><span>" + EnumTools.State.values()[usr.getUstate()] + "</span></td>");
                        result.append("<td class='link'><a href=\"javascript:enableuser('" + usr.getId() + "');\">启用</a>");
                    }
                    result.append("&nbsp;<a href=\"javascript:resetpwd('" + usr.getId() + "');\">重置密码</a>");
                    if (usr.getIsblack() == null) {
                        result.append("&nbsp;<a href=\"javascript:Blacklist('" + usr.getId() + "');\">加入黑名单</a>");
                    }

                    if (StringTools.trimNotEmpty(usr.getTel())) {
                        result.append("&nbsp;<a href=\"javascript:ChangeUserTel('" + usr.getId() + "');\">手机号更新</a></td></tr>");
                    } else {
                        result.append("</td></tr>");
                    }
                    num++;
                }
            } else {
                result.append("<tr><td colspan='8'>暂无注册用户</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getmembersLayuiJson", method = RequestMethod.POST)
    public LayuiDataTableResultBean getDeptsLayuiJson(HttpServletRequest request, HttpServletResponse response, HRUsers user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            Map<String, Object> map = memberService.getResults(page, limit, user);
            List<HRUsers> list = (List<HRUsers>)map.get("list");
            JSONArray jsonArray = new JSONArray();
            for (HRUsers usr :
                    list) {
                JSONObject item = new JSONObject();
                item.put("id",usr.getId());
                item.put("uname", usr.getUname());
                item.put("ucode", usr.getUcode());
                item.put("uemail", usr.getUemail());
                item.put("tel", usr.getTel());
                item.put("regtimeS", DateTools.toLenStr(usr.getAddtime()));
                item.put("lastlogintime", DateTools.toLenStr(usr.getLogintime()));
                item.put("hasresumeS", EnumTools.IsOrNot.values()[usr.getHasresume()]);
                item.put("ustateS", EnumTools.State.values()[usr.getUstate()]);
                jsonArray.add(item);
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //[end]

    //region [start] 修改手机号弹框
    @RequestMapping("/ChangeUserTel")
    public String ChangeTel(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            HRUsers user = memberService.getHrUser(id);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/member/ChangeTel";
    }
    //endregion

    //region [start] 保存用户电话
    @RequestMapping(value = "/ChangeTelAction", method = RequestMethod.POST)
    public void ChangeTelAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            String vcode=request.getParameter("vcode");
            String newTel=request.getParameter("newtel");

            HRUsers user = memberService.getHrUser(id);
            BaseUser usr = utilService.getSessionUser(request);
            if (usr == null) {
                utilService.printJsonResult(false, "请登录！", "no", response);
                return;
            }
            Object svcode=request.getSession().getAttribute("validcode");
            if (StringTools.trimNotEmpty(vcode)){
                if(!vcode.toLowerCase().equalsIgnoreCase(svcode.toString())){
                    utilService.printJsonResult(false, "验证码错误！", "no", response);
                    return;
                }
            }else{
                utilService.printJsonResult(false, "请输入验证码！", "no", response);
                return;
            }
            if (user != null) {
                List editList=new ArrayList();
                UserResume userResume=resumeService.getUserResume(user.getId());
               List<DUserResume> dUserResumeList=doResumeService.getDUserResumeByUserid(new String[]{user.getId()});
                user.setTel(newTel);
                editList.add(user);
                if(userResume!=null){
                    userResume.setTel(newTel);
                    editList.add(userResume);
                }
                if(dUserResumeList!=null&&dUserResumeList.size()>0){
                    for (DUserResume dUserResume : dUserResumeList) {
                        dUserResume.setTel(newTel);
                        editList.add(dUserResume);
                    }
                }
                if(editList.size()>0){
                    utilService.editList(editList);
                }

                utilService.printJsonResult(true, "手机号修改成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "该应聘者不存在", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //endregion [end]


    //[start] 黑名单管理
    @RequestMapping("/blacklist")
    public String BlackList(HttpServletRequest request, Model model) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/member/blacklist";
    }




    //获得应聘者信息
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getblacks", method = RequestMethod.POST)
    public void GetBlacks(HttpServletRequest request, HttpServletResponse response, HRUsers user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            user.setIsblack("true");

            Map<String, Object> map = memberService.getResults(page, perpage, user);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (HRUsers usr : (List<HRUsers>) object) {
                    result.append("<tr><td>" + (perpage * (page - 1) + num) + "</td>");
                    if (usr.getHasresume() == EnumTools.IsOrNot.是.ordinal()) {
                        result.append("<td class='link'><a target='_blank' href='/Do/SZResume/ViewResumeCardno?cardno=" + usr.getUcode() + "'>" + usr.getUname() + "</a></td>");
                    } else {
                        result.append("<td>" + usr.getUname() + "</td>");
                    }
                    result.append("<td>" + usr.getUcode() + "</td>");
                    result.append("<td>" + usr.getUemail() + "</td>");
                    result.append("<td>" + DateTools.toLenStr(usr.getAddtime()) + "</td>");
                    result.append("<td>" + DateTools.toLenStr(usr.getBlacktime()) + "</td>");
                    result.append("<td>" + usr.getBlackreason() + "</td>");
                    result.append("<td class='link'><a href=\"javascript:blackuser('" + usr.getId() + "');\">移除黑名单</a></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr><td colspan='8'>暂无黑名单用户</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getblacksLayuiJson", method = RequestMethod.POST)
    public LayuiDataTableResultBean getblacksLayuiJson(HttpServletRequest request, HttpServletResponse response, HRUsers user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            user.setIsblack("true");

            Map<String, Object> map = memberService.getResults(page, limit, user);
            List<HRUsers> list = (List<HRUsers>)map.get("list");
            JSONArray jsonArray = new JSONArray();
            for (HRUsers usr :
                    list) {
                JSONObject item = new JSONObject();
                item.put("id",usr.getId());
                item.put("uname", usr.getUname());
                item.put("ucode", usr.getUcode());
                item.put("uemail", usr.getUemail());
                item.put("regtimeS", DateTools.toLenStr(usr.getAddtime()));
                item.put("blacktime", DateTools.toLenStr(usr.getBlacktime()));
                item.put("blackreason", usr.getBlackreason());
                jsonArray.add(item);
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //[end]

    //[start] 重置密码
    @RequestMapping(value = "/ChangePwdAction", method = RequestMethod.POST)
    public void ChangePwdAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            HRUsers user = memberService.getHrUser(id);
            if (user != null) {
                String pwd = StringTools.GetMD5Code("111111");
                user.setUpwd(pwd);
                utilService.editObject(user);
                utilService.printJsonResult(true, "密码重置成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "该应聘者不存在", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 禁用/启用
    @RequestMapping(value = "/EnableAction", method = RequestMethod.POST)
    public void EnableAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            HRUsers user = memberService.getHrUser(id);
            if (user != null) {
                if (user.getUstate() == EnumTools.State.启用.ordinal())
                    user.setUstate(EnumTools.State.禁用.ordinal());
                else
                    user.setUstate(EnumTools.State.启用.ordinal());
                utilService.editObject(user);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "该应聘者不存在", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 加入黑名单
    @RequestMapping("/black")
    public String Black(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            HRUsers user = memberService.getHrUser(id);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/member/black";
    }

    @RequestMapping(value = "/BlackAction", method = RequestMethod.POST)
    public void BlackAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            String blackreason = request.getParameter("blackreason").trim();
            HRUsers usr = memberService.getHrUser(id);
            if (usr != null) {
                usr.setIsblack("true");
                usr.setBlacktime(new Date());
                usr.setBlackreason(blackreason);
                utilService.editObject(usr);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "非法访问", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }
    //[end]

    //[start] 移除黑名单
    @RequestMapping(value = "/OutBlackAction", method = RequestMethod.POST)
    public void OutBlackAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            HRUsers usr = memberService.getHrUser(id);
            if (usr != null) {
                usr.setIsblack(null);
                usr.setBlacktime(null);
                usr.setBlackreason(null);
                utilService.editObject(usr);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "非法访问", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }
    //[end]

}
